﻿'
' Will Strohl (will.strohl@gmail.com)
' http://www.willstrohl.com
'
'Copyright (c) 2011, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of Will Strohl, Open Graph for DotNetNuke, nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.UI.Skins.Controls
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.FileSystem
Imports DotNetNuke.Entities.Modules
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Web.UI
Imports WillStrohl.Modules.OpenGraph.OpenGraphController

Namespace WillStrohl.Modules.OpenGraph

    Partial Public MustInherit Class DefaultView
        Inherits WnsPortalModuleBase
        Implements IActionable

#Region " Private Members "

        Private Const EDIT_SETTINGS_KEY As String = "EditSettings.Text"
        Private Const EDIT_PAGE_KEY As String = "Edit"
        Private Const SETTINGS_MISSING_ERROR As String = "SettingsMissing.ErrorMessage"
        Private Const HTTP_PREFIX As String = "http://"

#End Region

#Region " Private Properties "



#End Region

#Region " Event Handlers "

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Not Page.IsPostBack Then
                    Me.BindData()
                End If
            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc, Me.IsEditable)
            End Try
        End Sub

#End Region

#Region " Helper Methods "

        Private Sub BindData()

            LocalizeModule()

            If Not SettingsAvailable() Then
                Skins.Skin.AddModuleMessage(Me, GetLocalizedString(SETTINGS_MISSING_ERROR), ModuleMessage.ModuleMessageType.RedError)
            Else

                Try

                    Dim sb As New StringBuilder(30)
                    Dim blnShowImageMessage As Boolean = False
                    Dim blnShowFacebookMessage As Boolean = False

                    sb.Append("<script language=""javascript"" type=""text/javascript"">/*<![CDATA[*/ ")
                    sb.Append(Environment.NewLine)

                    sb.Append("jQuery(document).ready(function () { ")
                    sb.Append(Environment.NewLine)

                    If Not String.IsNullOrEmpty(Title) Then
                        sb.AppendFormat("if (jQuery('meta[property=\'og:title\']').length == 0) jQuery('head').append('<meta property=""og:title"" content=""{0}""/>'); ", CleanValueForClientScript(Title))
                        sb.Append(Environment.NewLine)
                    End If

                    If Not String.IsNullOrEmpty(SiteType) Then
                        sb.AppendFormat("if (jQuery('meta[property=\'og:type\']').length == 0) jQuery('head').append('<meta property=""og:type"" content=""{0}""/>'); ", SiteType)
                        sb.Append(Environment.NewLine)
                    End If

                    If Not String.IsNullOrEmpty(Url) Then
                        sb.AppendFormat("if (jQuery('meta[property=\'og:url\']').length == 0) jQuery('head').append('<meta property=""og:url"" content=""{0}""/>'); ", Url)
                        sb.Append(Environment.NewLine)
                    End If

                    If Not String.IsNullOrEmpty(Image) Then

                        If Regex.IsMatch(Image, "^FileID=\d+$", RegexOptions.IgnoreCase) Then

                            Dim strFileId As String = Regex.Match(Image, "\d+", RegexOptions.IgnoreCase).Value
                            Dim oImage As IFileInfo = FileManager.Instance().GetFile(Integer.Parse(strFileId, Globalization.NumberStyles.Integer))

                            If Not oImage Is Nothing Then
                                ' only append the file tag if the file still exists
                                Dim strPath As String = String.Concat(HTTP_PREFIX, PortalSettings.PortalAlias.HTTPAlias, FileManager.Instance().GetUrl(oImage))

                                sb.AppendFormat("if (jQuery('meta[property=\'og:image\']').length == 0) jQuery('head').append('<meta property=""og:image"" content=""{0}""/>'); ", strPath)
                                sb.Append(Environment.NewLine)
                            Else
                                ' file doesn't exist any longer - delete the reference
                                If Not Settings(OG_IMAGE_SETTING) Is Nothing Then
                                    Dim objModules As New ModuleController
                                    objModules.DeleteTabModuleSetting(TabModuleId, OG_IMAGE_SETTING)
                                End If
                            End If

                        Else

                            sb.AppendFormat("if (jQuery('meta[property=\'og:image\']').length == 0) jQuery('head').append('<meta property=""og:image"" content=""{0}""/>'); ", Image)

                        End If
                    Else

                        blnShowImageMessage = True

                    End If

                    If Not String.IsNullOrEmpty(SiteName) Then
                        sb.AppendFormat("if (jQuery('meta[property=\'og:site_name\']').length == 0) jQuery('head').append('<meta property=""og:site_name"" content=""{0}""/>'); ", CleanValueForClientScript(SiteName))
                        sb.Append(Environment.NewLine)
                    End If

                    If Not String.IsNullOrEmpty(FacebookAdmins) Then
                        sb.AppendFormat("if (jQuery('meta[property=\'fb:admins\']').length == 0) jQuery('head').append('<meta property=""fb:admins"" content=""{0}""/>'); ", FacebookAdmins)
                        sb.Append(Environment.NewLine)
                    End If

                    If Not String.IsNullOrEmpty(FacebookAppId) Then
                        sb.AppendFormat("if (jQuery('meta[property=\'fb:app_id\']').length == 0) jQuery('head').append('<meta property=""fb:app_id"" content=""{0}""/>'); ", FacebookAppId)
                        sb.Append(Environment.NewLine)
                    End If

                    If String.IsNullOrEmpty(FacebookAdmins) Or String.IsNullOrEmpty(FacebookAppId) Then
                        blnShowFacebookMessage = True
                    End If

                    If Not String.IsNullOrEmpty(Description) Then
                        sb.AppendFormat("if (jQuery('meta[property=\'og:description\']').length == 0) jQuery('head').append('<meta property=""og:description"" content=""{0}""/>'); ", CleanValueForClientScript(Description))
                        sb.Append(Environment.NewLine)
                    End If

                    sb.Append("}); ")
                    sb.Append(Environment.NewLine)

                    sb.Append("/*]]>*/</script> ")
                    sb.Append(Environment.NewLine)

                    phOpenGraph.Controls.Add(New LiteralControl(sb.ToString()))

                    ' notify the content editor of the success
                    If Me.IsEditable AndAlso PortalSettings.UserMode = Entities.Portals.PortalSettings.Mode.Edit Then
                        Skins.Skin.AddModuleMessage(Me, GetLocalizedString("OpenGraph.Success"), ModuleMessage.ModuleMessageType.GreenSuccess)
                    End If

                    If blnShowImageMessage Then
                        ' warn the admin that the image really is strongly suggested
                        If Me.IsEditable AndAlso PortalSettings.UserMode = Entities.Portals.PortalSettings.Mode.Edit Then
                            Skins.Skin.AddModuleMessage(Me, GetLocalizedString("ImageMissing.Warning"), ModuleMessage.ModuleMessageType.YellowWarning)
                        End If
                    End If

                    If blnShowFacebookMessage Then
                        ' warn the admin that the Facebook settings are strongly suggested
                        If Me.IsEditable AndAlso PortalSettings.UserMode = Entities.Portals.PortalSettings.Mode.Edit Then
                            Skins.Skin.AddModuleMessage(Me, GetLocalizedString("FacebookMissing.Warning"), ModuleMessage.ModuleMessageType.YellowWarning)
                        End If
                    End If

                Catch ex As Exception
                    ProcessModuleLoadException(Me, ex, IsEditable)
                End Try
            End If

        End Sub

        Private Sub LocalizeModule()



        End Sub

        Private Function SettingsAvailable() As Boolean

            Return Not (String.IsNullOrEmpty(Title) Or String.IsNullOrEmpty(Description) Or String.IsNullOrEmpty(Url))

        End Function

        Private Function CleanValueForClientScript(ByVal Value As String) As String

            Value = Regex.Replace(Value, "'", "\'")
            Return Value

        End Function

#End Region

#Region " IActionable Implementation "

        Public ReadOnly Property ModuleActions() As Actions.ModuleActionCollection Implements IActionable.ModuleActions
            Get
                Dim oActions As New Actions.ModuleActionCollection
                oActions.Add(GetNextActionID, Me.GetLocalizedString(EDIT_SETTINGS_KEY), _
                    String.Empty, String.Empty, String.Empty, _
                    EditUrl(String.Empty, String.Empty, EDIT_PAGE_KEY), _
                    False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)

                Return oActions
            End Get
        End Property

#End Region

    End Class

End Namespace